#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# description: 单例模式的实现


info = {}

def singleton(class_name):
    def inner(*args, **kwargs):
        # 若类对象不在字典中，则说明还未创建
        if class_name not in info:
            info[class_name] = class_name(*args, **kwargs)
        return info[class_name]
    return inner


class Person:
    """定义一个人"""
    flag = True
    obj = None

    def __new__(cls, *args, **kwargs):
        if cls.obj is None:
            cls.obj = object.__new__(cls)
        return cls.obj

    def __init__(self, name, age):
        if Person.flag:
            self.name = name
            self.__age = age
            Person.flag = False

    def show(self):
        print(f"my name is {self.name}, my age is {self.__age} years old")

@singleton
class Dog:
    """狗🐕"""
    def __init__(self, name):
        self.name = name

    def run(self):
        print(f"{self.name} 正在草地上奔跑...")


print('测试一'.center(25, '*'))
p1 = Person("张三", 27)
p2 = Person("李四", 25)
print("p1 %d, p2 %d" %(id(p1), id(p2)))
p1.show()
p2.show()
print('测试二'.center(25, '='))
d1 = Dog('中华田园犬')
d2 = Dog('哈士奇')
d1.run()
d2.run()
